import * as types from "./types";

export default {
    namespaced: true,
  state: {
    todos: [
      { id: 1, title: "吃饭", done: true },
      { id: 2, title: "睡觉", done: false },
    ],
    currentFilter: "全部",
  },
  getters: {
    filterTodos(state) {
      switch (state.currentFilter) {
        case "已完成":
          return state.todos.filter((todo) => todo.done);
        case "未完成":
          return state.todos.filter((todo) => !todo.done);
        case "全部":
        default:
          return state.todos;
      }
    },
  },
  mutations: {
    // 添加todo
    // payload：title的字符串
    [types.ADD_TODO](state, title) {       // 'todo/addTodo'
      state.todos.push({ id: Date.now(), title, done: false });
    },

    // 更新todos 参数todo要求是一个todo对象
    [types.UPDATE_TODO](state, todo) {
      //  根据传进来的数据 找到数组中的对应项
      const index = state.todos.findIndex((item) => item.id === todo.id);
      if (index !== -1) {
        state.todos.splice(index, 1, todo);
      }
    },

    //  删除todos
    [types.DELETE_TODO](state, todo) {
      let index = -1;
      if (typeof todo === "number") {
        index = state.todos.findIndex((item) => item.id === todo);
      } else if (typeof todo === "object") {
        index = state.todos.findIndex((item) => item.id === todo.id);
      }

      if (index !== -1) {
        state.todos.splice(index, 1);
      }
    },

    // 改变筛选条件
    [types.CHANGE_FILTER](state, filter) {
      state.currentFilter = filter;
    },
  },
};
